package com.abe.mvp.view.activity;

import java.util.ArrayList;
import java.util.List;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.abe.config.Constants;
import com.abe.config.Interpolator;
import com.abe.config.StrengthtrainerSericalPortUtils;
import com.abe.mvp.contact.SerialPortContact;
import com.abe.mvp.contact.SocketContact;
import com.abe.mvp.model.bean.MainExerciseBean;
import com.abe.mvp.model.bean.exercise.ExerciseSTGroupBean;
import com.abe.mvp.model.bean.exercise.ExerciseSTNodeBean;
import com.abe.mvp.view.activity.base.BaseActivity;
import com.abe.mvp.view.adapter.MainExerciseInfoAdapter;
import com.abe.strengthtrainer.R;
import com.abe.utils.CRCChecker;
import com.abe.utils.NormalUtils;
import com.abe.utils.ThreadPoolUtils;
import com.abe.view.MoveAnimCurveOldView;
import com.abe.view.MoveAnimCurveOldView.CurveControl;

@ContentView(R.layout.activity_st_main_ball_old)
public abstract class MainBallViewOldOldActivity extends BaseActivity implements
		CurveControl, SerialPortContact.View, SocketContact.View {
	/** 曲线状态 */
	protected boolean isMove = false;
	/** 记录状态（记录锻炼者，最高位置，重量，事件相关信息，用于生生成曲线与格式化） */
	protected boolean isRecordEnd = false;
	/** 运动状态 */
	protected boolean isExercise = false;
	/** 锻炼器材设置的最大幅度（用来转换小球屏幕位置） */
	protected int customMaxHeight = 0;
	protected int currentCustomHeight = 0;
	protected Interpolator interpolator;
	/** 锻炼器材设置的重量 */
	protected int oldCustomWeight = 0;
	protected int currentCustomWeight = 0;
	/** 重量变化节点 */
	protected List<ExerciseSTNodeBean> nodeBeans;
	/** 锻炼数据展示 */
	protected List<MainExerciseBean> exerciseBeans;
	/** TODO 数据读取频率(ms) */
	protected static int readDataRate = 50;
	/** 插值频率(ms) */
	protected static int interpolatorDataRate = 1;
	/** 当前是否处于正在设置启停命令 */
	protected boolean isSetStartStopCommand = false;
	/** 锻炼数据 */
	protected ExerciseSTGroupBean groupBean;
	/** 锻炼时间（开始，结束） */
	protected long exerciseStartTime = 0, exerciseStopTime = 0;

	/** 启动成功 */
	public abstract void startSuccess();

	/** 停止成功 */
	public abstract void stopSuccess();

	/** 发送串口命令 */
	public abstract void sendSericalPortCommand(byte[] command);

	protected List<Integer> heights = new ArrayList<Integer>();
	protected List<Integer> times = new ArrayList<Integer>();
	protected List<Float> interpolator_heights = new ArrayList<Float>();
	protected int currentTime = 0;

	// protected StringBuilder //logBuilder = new StringBuilder();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initData();
		/** 曲线初始化 */
		macv.setCallBack(this);
		macv.setScreenMoveTime(3000);
	}

	private void initData() {
		show_exercise_button_back.setVisibility(View.VISIBLE);
		/** 状态初始化 */
		isMove = false;
		isRecordEnd = false;
		isExercise = false;
		groupBean = null;
		/** 提示信息初始化 */
		localCustomSendMessage(MAIN_REFRESH_SHOW,
				NormalUtils.getString(R.string.prompt_record_data));
		localCustomSendEmptyMessage(MAIN_REFRESH_SHOW_MSG);
		nodeBeans = new ArrayList<ExerciseSTNodeBean>();
		exerciseBeans = new ArrayList<MainExerciseBean>();
		int[] names = { R.string.common_count, R.string.common_weight };
		int[] values = { 0, 0 };
		for (int i = 0; i < 2; i++) {
			MainExerciseBean exerciseBean = new MainExerciseBean();
			exerciseBean.setName(NormalUtils.getString(names[i]));
			exerciseBean.setData(String.valueOf(values[i]));
			exerciseBeans.add(exerciseBean);
		}
		adapter = new MainExerciseInfoAdapter(this, exerciseBeans, scale);
		LayoutParams params = show_exercise_info_grid.getLayoutParams();
		params.width = (int) (scale * 400 * exerciseBeans.size());
		show_exercise_info_grid.setLayoutParams(params);
		show_exercise_info_grid.setAdapter(adapter);
	}

	@Override
	public void callStartMove() {
		isMove = true;
		localCustomSendEmptyMessage(EXERCISE_START);
	}

	@Override
	public void callRestartMove() {
		isMove = true;
		localCustomSendEmptyMessage(EXERCISE_UPDATE);
	}

	@Override
	public void callStopMove() {
		isMove = false;
		localCustomSendEmptyMessage(EXERCISE_STOP);
	}

	/** 请求启动 */
	public void requestStart() {
		if (!isExercise) {
			byte[] start = CRCChecker
					.getSendBuf(StrengthtrainerSericalPortUtils.SET_START);
			sendSericalPortCommand(start);
			// logBuilder.append("发送启动命令").append("\n");
			isSetStartStopCommand = true;
			localCustomSendMessage(MAIN_REFRESH_SHOW,
					NormalUtils.getString(R.string.prompt_curve_generating));
		}
	}

	/** 请求停止 */
	public void requestStop() {
		if (isExercise) {
			byte[] stop = CRCChecker
					.getSendBuf(StrengthtrainerSericalPortUtils.SET_STOP);
			sendSericalPortCommand(stop);
			// logBuilder.append("发送停止命令").append("\n");
			isSetStartStopCommand = true;
		}
	}

	/** 实时更新组数据 */
	protected void refreshExerciseGroupData(int count) {
		groupBean = new ExerciseSTGroupBean();
		int weight = 0;
		float calorie = 0;
		int nodeSize = nodeBeans.size();
		if (nodeSize == 0) {
			count = 0;
		} else if (nodeSize == 1) {
			weight = nodeBeans.get(0).getNodeWeight();
			calorie = Constants.getKcal(weight, customMaxHeight, count);
		} else {
			for (int i = 1; i < nodeSize; i++) {
				ExerciseSTNodeBean temPreviousBean = nodeBeans.get(i - 1);
				ExerciseSTNodeBean temBean = nodeBeans.get(i);
				int temWeight = (temBean.getNodeCount() - temPreviousBean
						.getNodeCount()) * temPreviousBean.getNodeWeight();
				if (temWeight > 0) {
					weight = weight + temWeight;
				}
				if (i == nodeSize - 1) {
					temWeight = (count - temBean.getNodeCount())
							* temBean.getNodeWeight();
					weight = weight + temWeight;
				}
			}
			calorie = Constants.getKcal(weight, customMaxHeight, count);
		}
		groupBean.setCount(count);
		groupBean.setWeight(weight);
		groupBean.setCalorie(calorie);
	}

	@Event(value = R.id.show_exercise_button_back, type = View.OnClickListener.class)
	private void back(View view) {
		if (isExercise) {
			requestStop();
		} else {
			back();
		}
	}

	private static final int EXERCISE_START = 0x901;
	private static final int EXERCISE_STOP = 0x902;
	private static final int EXERCISE_UPDATE = 0x903;
	/** 刷新重量 */
	protected static final int MAIN_REFRESH_WEIGHT = 0x904;
	/** 刷新次数 */
	protected static final int MAIN_REFRESH_COUNT = 0x905;
	/** 刷新小球位置 */
	protected static final int MAIN_REFRESH_BALL_POS = 0x906;
	/** 插值刷新小球位置 */
	protected static final int MAIN_REFRESH_Interpolator_BALL_POS = 0x907;
	/** 发 */
	protected static final int MAIN_REFRESH_SEND = 0x908;
	/** 收 */
	protected static final int MAIN_REFRESH_RECEIVE = 0x909;
	/** show */
	protected static final int MAIN_REFRESH_SHOW = 0x910;
	/** show message */
	protected static final int MAIN_REFRESH_SHOW_MSG = 0x911;
	/** show curve */
	protected static final int MAIN_REFRESH_SHOW_CURVE = 0x912;

	protected void localCustomSendEmptyMessage(int what) {
		new CustomHander(Looper.getMainLooper()).sendEmptyMessage(what);
	}

	protected void localCustomSendMessage(int what, Object object) {
		new CustomHander(Looper.getMainLooper()).sendMessage(NormalUtils
				.getMessage(what, object));
	}

	class CustomHander extends Handler {
		public CustomHander(Looper looper) {
			super(looper);
		}

		public void handleMessage(Message msg) {
			switch (msg.what) {
			case EXERCISE_START:
				ThreadPoolUtils.execute(macv);
				break;
			case EXERCISE_STOP:
				macv.stopMove();
				break;
			case EXERCISE_UPDATE:
				macv.restartMove();
				break;
			case MAIN_REFRESH_WEIGHT: {
				MainExerciseBean temBean = exerciseBeans.get(1);
				temBean.setData(msg.obj.toString());
				exerciseBeans.set(1, temBean);
				adapter.notifyDataSetChanged();
			}
				break;
			case MAIN_REFRESH_COUNT: {
				MainExerciseBean temBean = exerciseBeans.get(0);
				temBean.setData(msg.obj.toString());
				exerciseBeans.set(0, temBean);
				adapter.notifyDataSetChanged();
			}
				break;
			case MAIN_REFRESH_BALL_POS:
				heights.add(currentCustomHeight);
				localCustomSendMessage(MAIN_REFRESH_Interpolator_BALL_POS,
						currentCustomHeight);
				break;
			case MAIN_REFRESH_Interpolator_BALL_POS:
				float interpolatorBallHeight = (float) Double
						.parseDouble(msg.obj.toString());
				interpolator_heights.add(interpolatorBallHeight);
				if (interpolatorBallHeight > customMaxHeight) {
					macv.setBallScreenHeight(1);
				} else {
					macv.setBallScreenHeight(((float) customMaxHeight - (interpolatorBallHeight))
							/ (float) customMaxHeight);
				}
				break;
			case MAIN_REFRESH_SEND:
				show_message_01.setText(msg.obj.toString());
				break;
			case MAIN_REFRESH_RECEIVE:
				show_message_02.setText(msg.obj.toString());
				break;
			case MAIN_REFRESH_SHOW:
				prompt_message_text.setText(msg.obj.toString());
				break;
			case MAIN_REFRESH_SHOW_MSG:
				move_cure_layout.setVisibility(View.GONE);
				show_message_layout.setVisibility(View.VISIBLE);
				break;
			case MAIN_REFRESH_SHOW_CURVE:
				move_cure_layout.setVisibility(View.VISIBLE);
				show_message_layout.setVisibility(View.GONE);
				break;
			}
		}
	}

	protected class RefreshBallHeightThread implements Runnable {

		@Override
		public void run() {
			while (isExercise) {
				localCustomSendMessage(MAIN_REFRESH_Interpolator_BALL_POS,
						interpolator.Kalman_filter(currentCustomHeight));
				try {
					Thread.sleep(interpolatorDataRate);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			}
		}
	}

	@ViewInject(R.id.show_message_01)
	protected TextView show_message_01;
	@ViewInject(R.id.show_message_02)
	protected TextView show_message_02;
	@ViewInject(R.id.show_exercise_button_back)
	protected LinearLayout show_exercise_button_back;

	@ViewInject(R.id.show_message_layout)
	protected LinearLayout show_message_layout;
	@ViewInject(R.id.prompt_message_text)
	protected TextView prompt_message_text;

	@ViewInject(R.id.move_cure_layout)
	protected LinearLayout move_cure_layout;
	@ViewInject(R.id.macv)
	protected MoveAnimCurveOldView macv;
	@ViewInject(R.id.show_exercise_info_grid)
	protected GridView show_exercise_info_grid;
	protected MainExerciseInfoAdapter adapter;

	/********************************* 串口相关 **************************************/

	@Override
	public void onConnectSuccess() {
		// logBuilder.append("*******************").append("串口开启成功")
		// .append("*******************").append("\n");
	}

	@Override
	public void onCloseSuccess() {
		// logBuilder.append("*******************").append("串口关闭成功")
		// .append("*******************").append("\n");
	}

	@Override
	public void onSendDataSuccess() {
		// logBuilder.append("*******************").append("命令发送成功")
		// .append("*******************").append("\n");
	}

	@Override
	public void onError(String errorMsg) {
		// logBuilder.append("*******************").append(errorMsg)
		// .append("*******************").append("\n");
	}

	/********************************** socket相关 *************************************/

	@Override
	public void onSocketConnectSuccess() {

	}

	@Override
	public void onSocketCloseSuccess() {

	}

	@Override
	public void onSocketSendDataSuccess() {

	}

	@Override
	public void onSocketReceiveDataSuccess(String receiveMsg) {

	}
}
